package yf.mall.service.impl.app;

import com.yf.response.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import yf.mall.utils.StringUtil;
import yf.mall.dao.UserDao;
import yf.mall.entity.UserEntity;
import yf.mall.enums.LevelEnum;
import yf.mall.enums.UserStatusEnum;
import yf.mall.service.app.AppUserService;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class AppUserServiceImpl implements AppUserService {


    @Resource
    private UserDao userDao;

    @Override
    public UserEntity phoneRegister(String topCode, String phone) {
        if (!StringUtil.isPhone(phone)) {
            throw new RRException("手机号有误!");
        }
        if (StringUtil.isBlank(topCode)) { //统一放到公司卷卷下
            topCode = "15675234523";
//            throw new RRException("推荐人不存在");
        }
        UserEntity topUser = userDao.findByMobile(topCode);
        if (topUser == null) {
            throw new RRException("推荐人不存在");
        }
        UserEntity user = new UserEntity();
        user.setPid(topUser.getId());
        user.setMobile(phone);
        user.setCode(phone);
        user.setLevelId(LevelEnum.YK.levelId);//游客
        user.setStatus(UserStatusEnum.ACTIVE.getIndex());
        user.setTime(new Date());
        user.setPassword("888888");
        user.setRemark("APP小程序手机号注册");
        userDao.save(user);
        return user;
    }

    @Override
    public boolean signOff(Long userId, String reason) {
        if (userId == null) {
            return false;
        }
        log.info("用户{}操作注销账户，注销原因：{}", userId, reason);
        UserEntity update = new UserEntity();
        update.setId(userId);
        update.setStatus(UserStatusEnum.BAN.getIndex());
        update.setRemark(reason);
        return userDao.update(update) > 0;
    }
}
